package com.ruoyi.web.controller.wx_warehouseman;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.vqms.domain.VQMSVisitRecordYuchai;
import com.ruoyi.vqms.domain.dto.WarehouseDTO;
import com.ruoyi.vqms.service.IVQMSVisitRecordYuchaiService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 小程序访问记录（玉柴） 控制器
 */
@RestController
@RequestMapping("/wx/warehouseman/yuchai")
public class warehouseYuchaiController extends BaseController {

    @Autowired
    private IVQMSVisitRecordYuchaiService visitRecordYuchaiService;

    /**
     * 查询访问记录（玉柴）列表小程序
     */
    @RequestMapping("/list")
    public TableDataInfo list(VQMSVisitRecordYuchai vqmsVisitRecordYuchai){
        startPage();
        List<VQMSVisitRecordYuchai> list=visitRecordYuchaiService.wxSelectList(vqmsVisitRecordYuchai);
        return getDataTable(list);
    }

    /**
     * 根据id查询记录
     * @param vqmsVisitRecordYuchai
     * @return
     */
    @GetMapping("/getId")
    public AjaxResult getId(VQMSVisitRecordYuchai vqmsVisitRecordYuchai){
        VQMSVisitRecordYuchai visitRecordYuchai = visitRecordYuchaiService.getById(vqmsVisitRecordYuchai.getId());
        if (visitRecordYuchai == null){
            return AjaxResult.error("未查到访客记录");
        }
        return AjaxResult.success(visitRecordYuchai);
    }

    /**
     * 统计昨天访客总量
     * @return
     */
    @GetMapping("/getYesterday")
    public AjaxResult getYesterday(VQMSVisitRecordYuchai vqmsVisitRecordYuchai){
        if (vqmsVisitRecordYuchai.getRegisterWarehouse() != null){
            if (vqmsVisitRecordYuchai.getRegisterWarehouse().equals("南大门")){
                vqmsVisitRecordYuchai.setRegisterWarehouse("");
            }
        }

        return AjaxResult.success(visitRecordYuchaiService.statisticsYesterday(vqmsVisitRecordYuchai));
    }

    /**
     * 统计今天访客总量
     * @return
     */
    @GetMapping("/getToday")
    public AjaxResult getToday(VQMSVisitRecordYuchai vqmsVisitRecordYuchai){
        if (vqmsVisitRecordYuchai.getRegisterWarehouse() != null){
            if (vqmsVisitRecordYuchai.getRegisterWarehouse().equals("南大门")){
                vqmsVisitRecordYuchai.setRegisterWarehouse("");
            }
        }
        System.out.println("查询仓库字段-->"+vqmsVisitRecordYuchai.getRegisterWarehouse());
        return AjaxResult.success(visitRecordYuchaiService.statisticsToday(vqmsVisitRecordYuchai));
    }

    /**
     * 统计各仓库登记总量（空为‘南大门’）
     * @return
     */
    @GetMapping("/statisticalWarehouse")
    public AjaxResult statisticalWarehouse(){
        List<WarehouseDTO> list = visitRecordYuchaiService.statisticalWarehouse();
        return AjaxResult.success(list);
    }

    /**
     * 导出访问记录（玉柴）小程序
     */
    @Log(title = "导出访问记录（玉柴）小程序", businessType = BusinessType.EXPORT)
//    @PreAuthorize("@ss.hasPermi('vqms:visitRecord:yuchai:export')")
    @PostMapping("/wxExport")
    public AjaxResult wxExport(@RequestBody VQMSVisitRecordYuchai params, HttpServletResponse response) {
        List<VQMSVisitRecordYuchai> list=visitRecordYuchaiService.wxSelectList(params);
        ExcelUtil<VQMSVisitRecordYuchai> util = new ExcelUtil<>(VQMSVisitRecordYuchai.class);
        String filename = util.exportExcel(list, "玉柴访客记录").get("msg").toString();
        String downloadPath = RuoYiConfig.getDownloadPath() + filename;
        try {
            if (!FileUtils.checkAllowDownload(downloadPath)) {
                return AjaxResult.error("资源文件("+filename+")非法，不允许下载。 ");
            }
            FileUtils.writeBytes(downloadPath, response.getOutputStream());
            return AjaxResult.success(filename);
        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResult.error(e.getMessage());
        }
    }


    /**
     * 导出访问记录（玉柴）小程序(选中)
     */
    @Log(title = "导出访问记录（玉柴）小程序(选中)", businessType = BusinessType.DELETE)
    @PostMapping(value = "/selectedExport")
    public AjaxResult selectedExport(@RequestBody Long[] ids, HttpServletResponse response) {

        List<VQMSVisitRecordYuchai> list = new ArrayList<>();
        VQMSVisitRecordYuchai visitRecordYuchai = new VQMSVisitRecordYuchai();
        if (ids != null && ids.length != 0){

            for (Long id : ids) { // 遍历数组
                visitRecordYuchai = visitRecordYuchaiService.getById(id);
                list.add(visitRecordYuchai);
            }
            System.out.println("原数组--》"+list);
            List<VQMSVisitRecordYuchai> sortedList = list.stream()
                    .sorted(Comparator.comparing(
                            VQMSVisitRecordYuchai::getCreateTime,
                            Comparator.nullsFirst(Comparator.naturalOrder())
                    ))
                    .collect(Collectors.toList());
            System.out.println("新数组--》"+sortedList);
            ExcelUtil<VQMSVisitRecordYuchai> util = new ExcelUtil<>(VQMSVisitRecordYuchai.class);
            String filename = util.exportExcel(sortedList, "玉柴访客记录").get("msg").toString();
            String downloadPath = RuoYiConfig.getDownloadPath() + filename;
            try {
                if (!FileUtils.checkAllowDownload(downloadPath)) {
                    return AjaxResult.error("资源文件("+filename+")非法，不允许下载。 ");
                }
                FileUtils.writeBytes(downloadPath, response.getOutputStream());
                return AjaxResult.success(filename);
            } catch (IOException e) {
                e.printStackTrace();
                return AjaxResult.error(e.getMessage());
            }

        } else {
            return AjaxResult.error("选中项为空");
        }

    }

}
